package com.feng.web.admin;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import com.feng.entity.Admin;
import com.feng.service.ServeAdminLogin;
import com.feng.util.DateUtil;
import com.feng.util.StringUtil;
import com.feng.util.web.ServletUtil;

public class login extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = ServletUtil.getSession(req);
		Admin a = (Admin) session.getAttribute("account");
		if(a!=null){
			ServletUtil.forword(req, resp, "admin/index");
		}else{
			ServletUtil.redirect(resp, "../admin.jspx?statu=10002");
		}
	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("username");
		String pwd = req.getParameter("pwd");
		if(!StringUtil.isempty(name)&&!StringUtil.isempty(pwd)){
			ServeAdminLogin login = new ServeAdminLogin();
			Admin a = login.findByName(name);
			if(a!=null && a.getPassword().equals(DigestUtils.shaHex(pwd))){
				
				HttpSession session = ServletUtil.getSession(req);
				session.setAttribute("account", a);
				a.setIp(ServletUtil.getIp(req));
				a.setLastAccessTime(DateUtil.getDate());
				login.update(a);
				ServletUtil.forword(req, resp, "admin/index");
			}else{
				ServletUtil.redirect(resp, "../admin.jspx?statu=10001");
			}
		}else{
			ServletUtil.redirect(resp, "../admin.jspx?statu=10002");
		}
		
	}
}
